package com.qf.ability.auth.application;

import com.qf.common.auth.token.MyTokenEnhancer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;
import org.springframework.security.oauth2.provider.token.TokenEnhancerChain;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;

import java.util.ArrayList;
import java.util.List;

/**
 * 认证服务器的核心配置
 */
@Configuration
@EnableAuthorizationServer
public class AuthServerConfiguration extends AuthorizationServerConfigurerAdapter {

    @Autowired
    private TokenStore tokenStore;

    @Autowired
    private JwtAccessTokenConverter getJwtAccessTokenConverter;

    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private MyTokenEnhancer tokenEnhancer;

    /**
     * 身份认证管理器
     */
    @Autowired
    private AuthenticationManager authenticationManager;

    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        security
                //基于内存的方式保存令牌的话，需要打开check_token的端口
//                .checkTokenAccess("permitAll()")
                //允许client_id和client_secret 随着表单参数一起提交
                .allowFormAuthenticationForClients();
    }

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients
                .inMemory()
                .withClient("system")
                .secret(passwordEncoder.encode("system"))
                .authorizedGrantTypes("password", "refresh_token")//授权类型
                .accessTokenValiditySeconds(3600)
                .refreshTokenValiditySeconds(7200)
                .redirectUris("http://www.baidu.com")
                .scopes("all")
                .and()
                .withClient("wechat")
                .secret(passwordEncoder.encode("wechat"))
                .authorizedGrantTypes("password", "refresh_token")//授权类型
                .accessTokenValiditySeconds(3600)
                .refreshTokenValiditySeconds(7200)
                .redirectUris("http://www.baidu.com")
                .scopes("all");
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {

        //准备一个增强器链 - 多个增强器起作用
        TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain();
        List<TokenEnhancer> tokenEnhancers = new ArrayList<>();
        tokenEnhancers.add(tokenEnhancer);
        tokenEnhancers.add(getJwtAccessTokenConverter);
        tokenEnhancerChain.setTokenEnhancers(tokenEnhancers);

        endpoints
                //负责令牌的存储方式
                .tokenStore(tokenStore)
                //负责令牌的生成方式
//                .accessTokenConverter(getJwtAccessTokenConverter)
                //为了刷新令牌,刷新令牌时，不会调用authenticationManager重新进行身份认证，而是通过sysUserService直接获取用户的身份信息
                .userDetailsService(userDetailsService)
                //将security的身份认证管理器 托管给 Oauth2
                .authenticationManager(authenticationManager)
                //设置令牌增强器
                .tokenEnhancer(tokenEnhancerChain);
    }
}
